package com.example.event;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.event.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private long startTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.tvResult.setText("按下了按钮-基于监听机制的事件处理");
            }
        });
        startTime = System.currentTimeMillis();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_0:
                binding.tvResult.setText("按下了【0】");
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                binding.tvResult.setText("按下了【音量+】");
                return true;
            case KeyEvent.KEYCODE_A:
                binding.tvResult.setText("按下了【a】");
                return true;
            case KeyEvent.KEYCODE_BACK:
                if (event.getRepeatCount() == 0) {
                    if ((System.currentTimeMillis() - startTime) > 2000) {
                        Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_LONG).show();
                        startTime = System.currentTimeMillis();
                    } else {
                        finish();
                    }
                }
                return true;
            default:
                binding.tvResult.setText("按下的键盘码【" + keyCode + "】");
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        binding.tvResult.setText("当前坐标：【" + String.format("%.2f", event.getX()) + ", " +
                String.format("%.2f", event.getY()) + "】");
        return super.onTouchEvent(event);
    }
}